package com.raorao.config.controller;

import com.raorao.config.controller.Model.FileAddRequest;
import com.raorao.config.controller.Model.ResponseEntity;
import com.raorao.config.controller.Model.ResultState;
import com.raorao.config.dao.pojo.FileInfo;
import com.raorao.config.dao.repository.FileInfoRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author raorao
 * @version 1.0
 * @description: 文件控制器
 * @date 2021/11/26 14:52
 */
@RequestMapping("file")
@Api(tags = "文件控制器")
@RestController
public class FileController {
    @Autowired
    private FileInfoRepository repository;

    @ApiOperation("添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "info", value = "文件信息", required = true)
    })
    @PostMapping("add")
    public ResponseEntity<FileInfo> add(@Validated FileAddRequest info){
        FileInfo fileInfo=new FileInfo();
        BeanUtils.copyProperties(info,fileInfo);
        fileInfo.setId(null);
        fileInfo.setCreateAt(new Date());
        fileInfo.setUpdateAt(new Date());
        repository.save(fileInfo);
        return ResponseEntity.success(fileInfo);
    }

    @ApiOperation("修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "info", value = "文件信息", required = true)
    })
    @PostMapping("edit")
    public ResponseEntity<FileInfo> edit(@Validated @RequestBody FileInfo info){
        repository.save(info);
        return ResponseEntity.success(info);
    }

    @ApiOperation("删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true)
    })
    @DeleteMapping("删除")
    public ResponseEntity<ResultState> add(@RequestParam("id") Integer id){
        repository.deleteById(id);
        return ResponseEntity.success(ResultState.success());
    }

    @ApiOperation("根据项目id查询所有")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "项目id", required = true)
    })
    @GetMapping("listByProjectId")
    public ResponseEntity<List<FileInfo>> listByPId(@RequestParam("projectId") Integer projectId){
        List<FileInfo> byProjectId = repository.findByProjectIdAndIsDelete(projectId,false);
        return ResponseEntity.success(byProjectId);
    }
}
